<template>
  <view class="detail-container">
    <!-- 顶部导航栏 -->
    <view class="detail-header">
      <view class="header-back" @click="navigateBack">
      </view>
      <view class="header-title">工单详情</view>
      <view class="header-right"></view>
    </view>

    <!-- 加载中提示 -->
    <view class="loading" v-if="isLoading">
      <text class="loading-icon">⏳</text>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 工单详情内容 -->
    <scroll-view class="detail-content" scroll-y v-else>
      <!-- 标题、状态、紧急程度 组合区域 -->
      <view class="detail-title-section">
        <view class="detail-title">{{ workorderDetail.title }}</view>
        <view class="title-bottom-bar">
          <view class="detail-status" :class="workorderDetail.statusClass">
            {{ workorderDetail.statusText }}
          </view>
          <!-- 紧急程度标签 -->
          <view class="detail-urgency" :class="workorderDetail.urgencyClass">
            {{ workorderDetail.urgencyText }}
          </view>
        </view>
      </view>

      <!-- 工单图片展示区域 - 始终显示区域，无图片时显示"无" -->
      <view class="detail-image-section">
        <view class="section-title">工单图片</view>
        <!-- 有图片时显示图片 -->
        <view class="image-container" v-if="workorderDetail.pic">
          <image 
            class="workorder-image" 
            :src="imageBaseUrl + workorderDetail.pic" 
            mode="widthFix" 
            @click="previewImage(imageBaseUrl + workorderDetail.pic)"
          ></image>
        </view>
        <!-- 无图片时显示"无" -->
        <view class="no-image" v-else>
          <text>无</text>
        </view>
      </view>

      <!-- 基本信息列表 -->
      <view class="detail-info">
        <view class="info-item">
          <view class="info-label">工单编号</view>
          <view class="info-value">{{ workorderDetail.id }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">提交人</view>
          <view class="info-value">{{ workorderDetail.name }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">联系电话</view>
          <view class="info-value">{{ workorderDetail.phone || '未填写' }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">地址</view>
          <view class="info-value">{{ workorderDetail.address || '未填写' }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">工单类型</view>
          <view class="info-value">{{ workorderDetail.typeText }}</view>
        </view>
        <!-- 紧急程度信息行 -->
        <view class="info-item">
          <view class="info-label">紧急程度</view>
          <view class="info-value" :class="workorderDetail.urgencyClass">
            {{ workorderDetail.urgencyText }}
          </view>
        </view>
        <view class="info-item">
          <view class="info-label">支付状态</view>
          <view class="info-value">{{ workorderDetail.payStatusText }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">创建时间</view>
          <view class="info-value">{{ workorderDetail.createTime }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">更新时间</view>
          <view class="info-value">{{ workorderDetail.updateTime }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">派单员ID</view>
          <view class="info-value">{{ workorderDetail.dispatcherId || '未派单' }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">接单人ID</view>
          <view class="info-value">{{ workorderDetail.employeeId || '未接单' }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">产品ID</view>
          <view class="info-value">{{ workorderDetail.productId || '无' }}</view>
        </view>
      </view>

      <!-- 问题描述 -->
      <view class="detail-section">
        <view class="section-title">问题描述</view>
        <view class="section-content">{{ workorderDetail.des || '无描述信息' }}</view>
      </view>

      <!-- 处理记录（非可抢状态时显示） -->
      <view class="detail-section" v-if="workorderDetail.status !== 0">
        <view class="section-title">处理记录</view>
        <view class="process-record" v-for="(record, index) in processRecords" :key="index">
          <view class="record-time">{{ record.time }}</view>
          <view class="record-content">{{ record.content }}</view>
          <view class="record-operator">操作员：{{ record.operator }}</view>
        </view>
      </view>
    </scroll-view>

    <!-- 操作按钮：仅当前员工已接单的处理中工单显示 -->
    <view 
      class="detail-footer" 
      v-if="!isLoading && workorderDetail.status === 1 && workorderDetail.employeeId === currentEmployeeId"
    >
      <button class="action-btn complete-btn" @click="markComplete">标记完成</button>
      <button class="action-btn reject-btn" @click="showRejectReasonDialog">拒绝工单</button>
    </view>

    <!-- 抢单按钮：仅可抢工单显示 -->
    <view class="detail-footer" v-if="!isLoading && workorderDetail.status === 0">
      <button class="grab-btn" @click="grabOrder" :disabled="isGrabbing">
        {{ isGrabbing ? '抢单中...' : '抢单' }}
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 图片基础访问URL（数据库路径需拼接此地址才能访问）
      imageBaseUrl: 'http://47.96.93.244:8084/',
      workorderId: '',          // 工单ID（从路由参数获取）
      workorderDetail: {},      // 工单详情数据（包含urgency、pic字段）
      processRecords: [],       // 处理记录
      isGrabbing: false,        // 抢单状态锁（防止重复点击）
      isLoading: true,          // 页面加载状态
      currentEmployeeId: null   // 当前登录员工ID
    };
  },
  onLoad(options) {
    // 获取路由参数中的工单ID
    this.workorderId = options.id;
    console.log('从路由获取的工单ID:', this.workorderId);

    // 验证工单ID有效性
    if (!this.workorderId || this.workorderId === 'undefined') {
      uni.showToast({ title: '未获取到工单ID，无法加载详情', icon: 'none' });
      setTimeout(() => uni.navigateBack(), 1500);
      return;
    }

    // 获取当前登录员工ID
    this.currentEmployeeId = uni.getStorageSync('employeeId');
    console.log('当前登录员工ID:', this.currentEmployeeId);

    // 加载工单详情
    this.getWorkorderDetail();
  },
  methods: {
    /**
     * 返回上一页
     */
    navigateBack() {
      uni.navigateBack();
    },

    /**
     * 获取工单详情
     */
    getWorkorderDetail() {
      uni.showLoading({ title: '加载中...' });
      this.isLoading = true;

      const requestUrl = `http://localhost:6013/order-client/api/workOrderInfo/get?id=${this.workorderId}`;

      uni.request({
        url: requestUrl,
        method: 'POST',
        header: { 'Content-Type': 'application/json' },
        success: (res) => {
          uni.hideLoading();
          this.isLoading = false;

          if (res.data?.code === 0) {
            const workorderData = res.data.data;
			 console.log('后端返回的图片路径：', workorderData.pic); // 新增：打印pic字段
            this.workorderDetail = this.mapWorkorderData(workorderData);
            this.generateProcessRecords();
          } else {
            uni.showToast({ title: res.data?.msg || '加载工单详情失败', icon: 'none' });
            this.simulateData(); // 接口失败时用模拟数据兜底
          }
        },
        fail: () => {
          uni.hideLoading();
          this.isLoading = false;
          uni.showToast({ title: '网络错误，无法获取工单详情', icon: 'none' });
          this.simulateData();
        }
      });
    },

    /**
     * 映射后端数据到前端格式
     */
    mapWorkorderData(rawData) {
      const statusMap = { 0: '待处理', 1: '处理中', 2: '已处理', null: '未知状态' };
      const typeMap = { 1: '维修', 2: '安装', null: '未知类型' };
      const payStatusMap = { 0: '未支付', 1: '已支付', 2: '退款中', 3: '已退款', null: '未设置' };
      const statusClassMap = { 0: 'status-pending', 1: 'status-processing', 2: 'status-handled' };
      // 紧急程度映射
      const urgencyMap = { 1: '普通', 2: '紧急', null: '未知' };
      const urgencyClassMap = { 1: 'urgency-ordinary', 2: 'urgency-urgent', null: 'urgency-unknown' };

      return {
        id: rawData.id,
        title: rawData.title || '无标题',
        des: rawData.des,
        name: rawData.name || '未知提交人',
        phone: rawData.phone,
        address: rawData.address,
        createTime: this.formatTime(rawData.createTime),
        updateTime: this.formatTime(rawData.updateTime),
        status: rawData.status,
        statusText: statusMap[rawData.status] || '未知状态',
        statusClass: statusClassMap[rawData.status] || '',
        type: rawData.type,
        typeText: typeMap[rawData.type],
        payStatus: rawData.payStatus,
        payStatusText: payStatusMap[rawData.payStatus],
        productId: rawData.productId,
        dispatcherId: rawData.dispatcherId,
        employeeId: rawData.employeeId,
        revision: rawData.revision,
        // 紧急程度相关字段
        urgency: rawData.priorityType,
        urgencyText: urgencyMap[rawData.priorityType] || '未知',
        urgencyClass: urgencyClassMap[rawData.priorityType] || 'urgency-unknown',
        // 工单图片
        pic: rawData.pic || ''
      };
    },

    /**
     * 生成处理记录
     */
    generateProcessRecords() {
      const { status, employeeId, createTime, des } = this.workorderDetail;
      const operator = employeeId === this.currentEmployeeId 
        ? `员工${employeeId}` 
        : employeeId ? `员工${employeeId}` : '系统';
      
      const iosSafeCreateTime = this.convertToIosSafeDate(createTime);
      const baseTime = new Date(iosSafeCreateTime).getTime();
      this.processRecords = [];

      const rejectReasonMatch = des ? des.match(/【拒绝原因：(.*?)】/) : null;
      const rejectReason = rejectReasonMatch ? rejectReasonMatch[1] : '';

      if (status === 0 && rejectReason) {
        this.processRecords.push(
          { time: this.formatTime(baseTime), content: '工单创建，等待接单', operator: '系统' },
          { time: this.formatTime(baseTime + 3600000), content: `工单被拒绝，原因：${rejectReason}`, operator },
          { time: this.formatTime(baseTime + 3700000), content: '工单回到待处理状态，可重新抢单', operator: '系统' }
        );
      } else if (status === 1) {
        this.processRecords.push(
          { time: this.formatTime(baseTime), content: '工单创建', operator: '系统' },
          { time: this.formatTime(baseTime + 1800000), content: `员工${employeeId}接单成功`, operator: '系统' },
          { time: this.formatTime(baseTime + 3600000), content: '工单处理中', operator }
        );
      } else if (status === 2) {
        this.processRecords.push(
          { time: this.formatTime(baseTime), content: '工单创建', operator: '系统' },
          { time: this.formatTime(baseTime + 1800000), content: `员工${employeeId}接单`, operator: '系统' },
          { time: this.formatTime(baseTime + 7200000), content: '工单处理完成', operator }
        );
      }
    },

    /**
     * 抢单操作
     */
    grabOrder() {
      if (this.isGrabbing || !this.currentEmployeeId) return;
      
      this.isGrabbing = true;
      uni.showLoading({ title: '抢单中...' });

      uni.request({
        url: 'http://localhost:6013/order-client/api/employeeInfo/grabOrder',
        method: 'POST',
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: {
          orderId: this.workorderDetail.id,
          employeeId: this.currentEmployeeId
        },
        success: (res) => {
          uni.hideLoading();
          this.isGrabbing = false;

          if (res.data?.code === 0) {
            uni.showModal({
              title: '成功',
              content: '抢单成功，已为您分配工单',
              showCancel: false,
              success: () => {
                this.getWorkorderDetail();
                uni.$emit('workorderStatusUpdated');
              }
            });
          } else {
            uni.showModal({
              title: '失败',
              content: res.data?.msg || '抢单失败，请重试',
              showCancel: false
            });
          }
        },
        fail: () => {
          uni.hideLoading();
          this.isGrabbing = false;
          uni.showToast({ title: '网络错误，抢单失败', icon: 'none' });
        }
      });
    },

    /**
     * 标记完成
     */
    markComplete() {
      uni.showModal({
        title: '标记完成',
        content: `确定将“${this.workorderDetail.title}”标记为已处理吗？`,
        success: (res) => {
          if (res.confirm) {
            this.callCompleteOrderApi();
          }
        }
      });
    },

    /**
     * 调用完成工单接口
     */
    callCompleteOrderApi() {
      const employeeId = this.currentEmployeeId;
      const orderId = this.workorderDetail.id;
      
      if (!employeeId || !orderId) {
        uni.showToast({ title: '参数错误，无法提交', icon: 'none' });
        return;
      }

      uni.showLoading({ title: '提交中...' });
      uni.request({
        url: 'http://localhost:6013/order-client/api/employeeInfo/completeOrder',
        method: 'POST',
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: { orderId, employeeId },
        success: (res) => {
          uni.hideLoading();
          
          if (res.data?.code === 0) {
            uni.showToast({ title: '标记为已处理成功', icon: 'success' });
            this.getWorkorderDetail();
            uni.$emit('workorderStatusUpdated');
          } else {
            uni.showToast({ title: res.data?.msg || '标记完成失败', icon: 'none' });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({ title: '网络错误，操作失败', icon: 'none' });
        }
      });
    },

    /**
     * 显示拒绝原因输入框
     */
    showRejectReasonDialog() {
      uni.showModal({
        title: '拒绝工单',
        content: '请输入拒绝原因',
        editable: true,
        placeholderText: '请输入拒绝原因（如：材料不足、地址错误等）',
        success: (res) => {
          if (res.confirm && res.content.trim()) {
            this.rejectOrder(res.content.trim());
          } else if (res.confirm && !res.content.trim()) {
            uni.showToast({ title: '拒绝原因不能为空', icon: 'none' });
          }
        }
      });
    },

    /**
     * 拒绝工单
     */
    rejectOrder(reason) {
      if (!this.workorderId) {
        uni.showToast({ title: '工单ID不存在，无法拒绝', icon: 'none' });
        return;
      }
      if (!this.currentEmployeeId) {
        uni.showToast({ title: '未获取到员工信息，无法拒绝', icon: 'none' });
        return;
      }
      if (!reason.trim()) {
        uni.showToast({ title: '拒绝原因不能为空', icon: 'none' });
        return;
      }

      uni.showLoading({ title: '提交中...' });
      uni.request({
        url: 'http://localhost:6013/order-client/api/workOrderInfo/reject',
        method: 'POST',
        data: {
          id: this.workorderId,
          employeeId: this.currentEmployeeId,
          reason: reason
        },
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        success: (res) => {
          uni.hideLoading();
          
          if (res.data?.code === 0) {
            uni.showToast({ title: '拒绝成功', icon: 'success' });
            this.getWorkorderDetail();
            uni.$emit('workorderStatusUpdated');
            setTimeout(() => uni.navigateBack(), 1500);
          } else {
            uni.showToast({ title: res.data?.msg || '拒绝失败', icon: 'none' });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          console.error('拒绝工单请求失败:', err);
          uni.showToast({ title: '网络连接失败，请重试', icon: 'none' });
        }
      });
    },

    /**
     * 预览工单图片
     */
    previewImage(imageUrl) {
      if (!imageUrl) return;
      uni.previewImage({
        urls: [imageUrl],
        current: imageUrl,
        fail: () => {
          uni.showToast({ title: '图片预览失败', icon: 'none' });
        }
      });
    },

    /**
     * 时间格式化工具
     */
    formatTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hour = date.getHours().toString().padStart(2, '0');
      const minute = date.getMinutes().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },

    /**
     * iOS日期兼容处理
     */
    convertToIosSafeDate(dateStr) {
      if (!dateStr) return '';
      return dateStr.replace(' ', 'T');
    },

    /**
     * 模拟数据
     */
    simulateData() {
      this.workorderDetail = {
        id: this.workorderId || 'SIM1001',
        title: '模拟处理中工单',
        des: '设备无法启动，需上门维修',
        name: '模拟用户',
        phone: '13800000000',
        address: '北京市海淀区测试街道',
        createTime: this.formatTime(Date.now() - 3600000),
        updateTime: this.formatTime(Date.now()),
        status: 1,
        statusText: '处理中',
        statusClass: 'status-processing',
        type: 1,
        typeText: '维修',
        payStatus: 0,
        payStatusText: '未支付',
        productId: 'PROD1001',
        dispatcherId: 'DIS1001',
        employeeId: this.currentEmployeeId || 'EMP1001',
        revision: 1,
        priorityType: 2,
        urgencyText: '紧急',
        urgencyClass: 'urgency-urgent',
        // 模拟有图片的情况，使用基础URL + 相对路径
        pic: 'group1/M00/00/00/rBjxQmjNAwaAREMKAAR0BUW2mqw327.jpg'
        // 如需测试无图片情况，可注释上面一行，打开下面一行
        // pic: ''
      };
      this.generateProcessRecords();
    }
  }
};
</script>

<style scoped>
/* 容器样式：100%视口高度，垂直布局 */
.detail-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

/* 头部导航栏样式 */
.detail-header {
  height: 88rpx;
  background-color: #5555ff;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  justify-content: space-between;
}
.header-back {
  width: 44rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.back-icon {
  font-size: 36rpx;
  color: #fff;
}
.header-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  color: #fff;
  font-weight: bold;
}
.header-right {
  width: 44rpx;
  height: 44rpx;
}

/* 加载中样式 */
.loading {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.loading-icon {
  font-size: 60rpx;
  color: #5555ff;
  margin-bottom: 20rpx;
}
.loading-text {
  font-size: 28rpx;
  color: #666;
}

/* 内容区域样式（滚动） */
.detail-content {
  flex: 1;
  padding: 24rpx;
}

/* 标题、状态、紧急程度 组合区域样式 */
.detail-title-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.detail-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
  line-height: 1.5;
}
.title-bottom-bar {
  display: flex;
  gap: 12rpx;
  align-items: center;
}
.detail-status {
  display: inline-block;
  font-size: 26rpx;
  padding: 6rpx 18rpx;
  border-radius: 18rpx;
}
.detail-urgency {
  display: inline-block;
  font-size: 26rpx;
  padding: 6rpx 18rpx;
  border-radius: 18rpx;
}

/* 图片展示区域样式 */
.detail-image-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.image-container {
  margin-top: 16rpx;
  border-radius: 8rpx;
  overflow: hidden;
  background-color: #fafafa;
}
.workorder-image {
  width: 100%;
  height: auto;
  min-height: 200rpx;
  object-fit: cover;
}
/* 无图片时的显示样式 */
.no-image {
  margin-top: 16rpx;
  padding: 40rpx 0;
  text-align: center;
  font-size: 28rpx;
  color: #999;
  background-color: #fafafa;
  border-radius: 8rpx;
}

/* 基本信息列表样式 */
.detail-info {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.info-item {
  display: flex;
  padding: 14rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}
.info-item:last-child {
  border-bottom: none;
}
.info-label {
  width: 220rpx;
  font-size: 28rpx;
  color: #666;
}
.info-value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  word-break: break-all;
}

/* 详情区块样式（问题描述、处理记录） */
.detail-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f5f5f5;
}
.section-content {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}

/* 处理记录样式 */
.process-record {
  padding: 18rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}
.process-record:last-child {
  border-bottom: none;
}
.record-time {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 8rpx;
}
.record-content {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
  line-height: 1.5;
}
.record-operator {
  font-size: 24rpx;
  color: #666;
}

/* 操作按钮区域样式 */
.detail-footer {
  padding: 24rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  justify-content: space-around;
}
.action-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 6rpx;
  border: none;
  color: #fff;
  font-size: 30rpx;
  margin: 0 10rpx;
}
.complete-btn {
  background-color: #4caf50;
}
.reject-btn {
  background-color: #f44336;
}

/* 抢单按钮样式 */
.grab-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #5555ff;
  color: #fff;
  font-size: 30rpx;
  border-radius: 6rpx;
  border: none;
}
.grab-btn:disabled {
  background-color: #b3b3ff;
  color: #f0f0f0;
}

/* 状态标签颜色样式 */
.status-pending { background-color: #e1f5fe; color: #0288d1; }
.status-processing { background-color: #bbdefb; color: #0d47a1; }
.status-handled { background-color: #c8e6c9; color: #388e3c; }

/* 紧急程度标签样式 */
.urgency-ordinary { background-color: #f5f5f5; color: #666; }
.urgency-urgent { background-color: #ffebee; color: #e53935; font-weight: bold; }
.urgency-unknown { background-color: #fff8e1; color: #ffb300; }
</style>
